package com.unknown.chainevent.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.util.Assert;
import org.web3j.abi.datatypes.Address;
import org.web3j.utils.Numeric;

public final class EventUtil {

  public static List<String> convertDataToValueList(String value) {
    Assert.isTrue(StrUtil.isNotEmpty(value), "value不能为空");
    Assert.isTrue(value.length() >= 66 && (value.length() - 2) % 64 == 0, "value格式错误");
    String valueNew = StrUtil.sub(value, 2, value.length()); // 截取去掉前两位
    return CollUtil.toList(StrUtil.split(valueNew, 64)).stream().map(item -> "0x" + item).collect(Collectors.toList());
  }

  /**
   * 转换一个数值为地址
   *
   * @param value
   * @return
   */
  public static BigInteger convertToBigInteger(String value) {
    Assert.isTrue(!StrUtil.isEmpty(value), "value不能为空");
    if (value.startsWith("0x")) {
      return Numeric.decodeQuantity(value);
    }
    return Numeric.decodeQuantity("0x" + value);
  }

  /**
   * 转换一个数值为地址
   *
   * @param value
   * @return
   */
  public static String convertToAddress(String value) {
    Assert.isTrue(!StrUtil.isEmpty(value), "value不能为空");
    if (value.length() == 66) {
      return new Address(value).toString();
    } else if (value.length() == 64) {
      return new Address("0x" + value).toString();
    }
    return "0x" + value.substring(26);
  }


  public static BigDecimal bigIntegerToBigDecimal(BigInteger value, int decimals) {
    return new BigDecimal(value).divide(BigDecimal.TEN.pow(decimals), new MathContext(decimals));
  }

  private EventUtil() {

  }
}
